print("player running")
try{
    var talkingTimer = 0;
    var g711a = new iot.codec.G711A();
    
    var PCM_BUFFER_SIZE = 160*100;//1second
    var pcmBuffer = Uint8Array.allocPlain(PCM_BUFFER_SIZE);
    var PLAY_BUF_SIZE = 160*30;//300ms
    var playing = false;
    var writePos = 0;
    function onPlayEnd(){
        print('onPlayEnd')
        playing = false;
    }
    function onTalkingEnd(){
        iot.audio.play_stop();
    }

    
    iot.os.parent.onMsg = function(msg) {
        try{         
            // if(talkingTimer){
            //     clearTimeout(talkingTimer);
            // }
            // talkingTimer = setTimeout(onTalkingEnd,500);
            var g711abuf = Duktape.dec('base64',msg);
            var pcmbuf = g711a.decode(g711abuf);
            var buflength = pcmbuf.length;
            //先写入缓存
            pcmBuffer.set(pcmbuf,writePos);
            writePos = writePos + buflength;
            if(!playing){
                if(writePos >= PLAY_BUF_SIZE){
                    playing = true;
                }
            }
            if(playing){
                iot.audio.play_pcm_stream(pcmBuffer.subarray(0,writePos),onPlayEnd);
                writePos = 0;
            }
        }catch(e){
            print(e);
        }
    };
}catch(e){
    print(e);
}

iot.os.loop()